package es.castorm.arch.web.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import com.sun.jersey.spi.spring.container.servlet.SpringServlet;

public abstract class AbstractWebAppInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {

		// Create the 'root' Spring application context
		AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
		rootContext.register(getConfig());

		// Manage the lifecycle of the root application context
		servletContext.addListener(new ContextLoaderListener(rootContext));

		// Register and map the jersey servlet
		ServletRegistration.Dynamic jerseyRegistration = servletContext.addServlet("jersey-serlvet", SpringServlet.class);
		jerseyRegistration.setInitParameter("com.sun.jersey.config.property.packages", getPackage());
		jerseyRegistration.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
		jerseyRegistration.setLoadOnStartup(1);
		jerseyRegistration.addMapping("/services/*");
	}

	public abstract Class<?> getConfig();

	public abstract String getPackage();
}